package com.blog.async;

import com.blog.model.EmailModel;
import com.blog.model.MailPropertiesModel;
import com.blog.pojo.Discuss;
import com.blog.service.DiscussService;
import com.blog.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author jiafujun
 * 2020-06-23 15:42:23
 **/
@Component
@Lazy
public class AsyncTask {

    @Autowired
    private DiscussService discussService;

    @Async
    public void sendEmail(Discuss record) {
        if (record.getReplyId() != null) {
            EmailModel discuss = discussService.getById(Integer.valueOf(record.getReplyId()));
            //判断消息是否存在，消息是否开启回复通知
            if (discuss != null && discuss.getNoticeSwitch().equals(1)) {
                MailPropertiesModel model = new MailPropertiesModel();
                model.setHost("smtp.qq.com");
                model.setPort(587);
                model.setUsername("1146527359@qq.com");
                model.setPassword("gokxemjwdzndhjcd");

                JavaMailSenderImpl javaMailSender = EmailUtil.getJavaMailSender(model);
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
                try {
                    String title = discuss.getArticleName();
                    if (discuss.getArticleName().length() > 15) {
                        title = discuss.getArticleName().substring(0, 15) + "...";
                    }
                    helper.setFrom("1146527359@qq.com");
                    helper.setTo(discuss.getEmail());
                    helper.setSubject("PoetryBlog博客");
                    helper.setText(EmailUtil.emailTemplate
                            .replace("${Commentator}$", discuss.getDiscussName())
                            .replace("${article}$", title)
                            .replace("${reply}$", record.getDiscussName())
                            .replace("${message}$", record.getContent())
                            .replace("${articleId}$", record.getArticleId().toString()), true);
                    javaMailSender.send(mimeMessage);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                System.out.println("-------------------------发送成功-------------------------");
            }
        }

    }
}
